import {
  Inject,
  Controller,
  Get,
  Post,
  Files,
  Query,
  Fields,
} from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
import { OrdersService } from '../service/orders.service';
import { PREFIX } from '../contanst';
import { BaseController } from './base.controller';
import { FileService } from '../service/file.service';
import { EXCEL_MAP } from '../contanst/orders';
import { OrdersProductsMapService } from '../service/ordersProductsMap.service';
import { toLower } from 'lodash';
import { Like } from 'typeorm';

const DESCRIPTION = '订单';

@Controller(PREFIX)
export class APIController extends BaseController {
  @Inject()
  ctx: Context;

  @Inject()
  ordersService: OrdersService;

  @Inject()
  ordersProductsMapService: OrdersProductsMapService;

  @Inject()
  file: FileService;

  @Get('/orders', {
    description: `${DESCRIPTION}列表`,
  })
  async index(
    @Query('size') size = 10,
    @Query('page') page = 1,
    @Query('data_date') data_date,
    @Query('store_name') store_name,
    @Query('order_number') order_number
  ) {
    const orders = await this.ordersService.page({
      data: {
        size,
        page,
        data_date,
        store_name: store_name && Like(`%${store_name}%`),
        order_number: order_number && Like(`%${order_number}%`),
      },
    });
    return this.success(orders);
  }

  @Post('/orders/import', {
    description: `${DESCRIPTION}导入`,
  })
  async import(
    @Files() files,
    @Fields('data_date') data_date,
    @Fields('store_name') store_name
  ) {
    const file = files[0];

    const data: any = await this.file.importExcel(file);
    const tableData = data?.[0]?.data;
    const tableHeader = tableData?.[0];
    const tableBody = tableData?.splice?.(1);
    const obj = {};
    Object.keys(EXCEL_MAP).forEach(key => {
      const index = tableHeader?.findIndex?.(
        item => toLower(item).trim() === toLower(key).trim()
      );

      obj[EXCEL_MAP[key]] = index;
    });

    const records: any[] = [];
    const mapRecords: any[] = [];
    tableBody.forEach(item => {
      const record: any = {};
      const mapRecord: any = {};
      Object.keys(obj).map(key => {
        if (key === 'product_code') {
          const arr = item[obj['product_code']]?.split?.('-') || [];
          const product_specification =
            parseInt(arr.at(-1)?.replace?.(/\t/g, '')) || null;
          record['product_code'] = arr
            .filter((i, k) => k !== arr.length - 1)
            ?.join('')
            ?.replace?.(/\t/g, '');
          record['product_specification'] = product_specification;
          record['product_unit'] = arr.at(-1).replace(/[0-9]+/g, '');
          mapRecord.product_specification = record['product_specification'];
          mapRecord.product_unit = record['product_unit'];
          mapRecord.product_code = record['product_code'];
        } else {
          record[key] = item[obj[key]]?.replace?.(/\t/g, '') || item[obj[key]];
          mapRecord[key] = record[key];
        }
      });
      record.store_name = store_name;
      record.data_date = data_date;
      mapRecord.store_name = store_name;
      mapRecord.data_date = data_date;

      records.push(record);
      mapRecords.push(mapRecord);
    });
    this.ordersService.upsert(records);
    this.ordersProductsMapService.upsert(mapRecords);

    return this.success();
  }
}
